/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package rs.fon.rapidminer.gui.panels.toolbar;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;

import rs.fon.rapidminer.gui.MainPanel;
import rs.fon.rapidminer.process.builder.generictree.GenericTreeProcessBuilder;
import rs.fon.rapidminer.serialization.ProcessDecoder;
import rs.fon.rapidminer.serialization.ProcessEncoder;

/**
 * 
 * @author Sasa
 */
public class Toolbar extends ToolbarPanel {

	@Override
	protected void loadFile() {
		JFileChooser jfc = new JFileChooser();
		String message = "";
		jfc.setDialogTitle("Open process from a file");
		FileFilter filter = new FileNameExtensionFilter("Process file (.pml)",
				"pml");
		jfc.addChoosableFileFilter(filter);
		int status = jfc.showOpenDialog(this);

		if (status == JFileChooser.APPROVE_OPTION) {
			selectedFile = jfc.getSelectedFile();
			MainPanel.setProcess(ProcessDecoder
					.decodeFromXMLToProces(selectedFile.getAbsolutePath()));
			message = "Process loaded from " + selectedFile.getName();
		} else
			message = "No file selected";
		JOptionPane.showMessageDialog(this, message);
	}

	@Override
	protected void saveFile() {
		JFileChooser jfc = new JFileChooser();
		jfc.setDialogType(JFileChooser.SAVE_DIALOG);
		jfc.setDialogTitle("Save process to a file");
		FileFilter filter = new FileNameExtensionFilter("Process file (.pml)",
				"pml");
		jfc.addChoosableFileFilter(filter);
		final int showSaveDialog = jfc.showDialog(this, "Save process");

		if (showSaveDialog == JFileChooser.APPROVE_OPTION) {
			FileFilter fileFilter = jfc.getFileFilter();
			if (fileFilter.getDescription().equals("Process file (.pml)")
					|| fileFilter.getDescription().equals("All Files")) {
				String file = jfc.getSelectedFile().getAbsolutePath() + ".pml";
				try {
					ProcessEncoder.encodeFormProcesToXML(
							MainPanel.getProcess(), file);
					JOptionPane.showMessageDialog(this, "Process saved.");
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		}

	}

	@Override
	protected void newFile() {
		String question = "Are you sure you want to start a new process? The current data will be lost.";
		int result = JOptionPane.showOptionDialog(this, question,
				"Confirmation", JOptionPane.YES_NO_OPTION,
				JOptionPane.WARNING_MESSAGE, null, null, null);

		if (result == JOptionPane.YES_OPTION)
			MainPanel.setProcess(new GenericTreeProcessBuilder().buildProces());
	}

}
